//
//  CZComment.swift
//  GZWeibo007
//
//  Created by shan on 15/12/24.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit

class CZComment: NSObject {
    
    var loading = false
    
    // 评论的ID
    var id: Int = 0
    
    // 评论的时间
    var created_at: String?
    
    // 用户信息
    var user: CZUser?
    
    // 评论的内容
    var text: String?
    
    // 行高
    var rowHeight: CGFloat?
    
    // 评论总数
    static var total_number: Int?

    init(loading: Bool) {
        self.loading = loading
        
        super.init()
    }
    
    init(dict: [String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        //        print("找不到key\(key)的值")
    }
    // KVC
    override func setValue(value: AnyObject?, forKey key: String) {
        
        if key == "user"{
            
            if let dict = value as? [String: AnyObject]{
                let userModel = CZUser(dict: dict)
                
                self.user = userModel
            }
            return
        }
        super.setValue(value, forKey: key)
    }
    
    override var description: String {
        let pops = ["id", "created_at","user", "text"]
        
        let dict = dictionaryWithValuesForKeys(pops)
        
        return "\n\t评论数据:\(dict)"
    }
    
    // MARK:- 加载数据
    class  func loadingComment(statusId: Int, since_id: Int, max_id: Int, finised: (comment: [CZComment]?, error: NSError?)->())
    {
        // 准备闭包
        CZNetworkTool.sharedInstance.loadComment(statusId, since_id: since_id, max_id: max_id) { (result, total_number, error) -> () in
            if error != nil || result == nil{
                
                finised(comment: nil, error: error)
                return
            }
            
            self.total_number = total_number
            
            // 有数据
            if let array = result?["comments"] as? [[String: AnyObject]]{
                // 创建一个数组,来存放转好的模型
                var comments = [CZComment]()
                
                //  遍历数组
                for dict in array {
                    let comment = CZComment(dict: dict)
                    comments.append(comment)
                    
                }
                // 返回有数据的模型
                finised(comment: comments, error: nil)
                
            } else {
                finised(comment: nil, error: nil)
            }
        }
    }
}
